package com.chuangjiangx.member.manager.client.web.coupon.compensator.Handle;

import com.alibaba.fastjson.JSONObject;
import com.chuangjiangx.member.coupon.ddd.domain.model.MbrCouponId;
import com.chuangjiangx.member.coupon.ddd.domain.model.MbrHasCouponId;
import com.chuangjiangx.member.coupon.ddd.domain.model.VerifyWxCodeCompensator;
import com.chuangjiangx.member.coupon.ddd.domain.service.CouponDomainService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;

import static com.chuangjiangx.commons.constant.CompensatorConstant.MEMBER_MANAGER_API_KEY;

/**
 * Created by Lenovo on 2018/9/7.
 * 微信核销失败错误处理
 */
@Slf4j
public class WxVerifyHandle implements Runnable {

    private CouponDomainService couponDomainService;
    private VerifyWxCodeCompensator verifyWxCodeCompensator;
    private StringRedisTemplate redisTemplate;

    public WxVerifyHandle(CouponDomainService couponDomainService,
                          VerifyWxCodeCompensator verifyWxCodeCompensator,
                          StringRedisTemplate redisTemplate){
        this.couponDomainService = couponDomainService;
        this.verifyWxCodeCompensator = verifyWxCodeCompensator;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void run() {
        log.info("开始错误补偿处理========================");
        log.info("错误发生时间：{} 错误发生类：{} 错误内容:{}",verifyWxCodeCompensator.getErrTime(),verifyWxCodeCompensator.getErrClass(),verifyWxCodeCompensator.getErrMessage());
        try{
            couponDomainService.verifyWxCode(new MbrCouponId(verifyWxCodeCompensator.getData().getMbrCouponId()),
                    new MbrHasCouponId(verifyWxCodeCompensator.getData().getMbrHasCouponId()));
            log.info("错误补偿处理结束========================");
        }catch (Exception e){
            e.printStackTrace();
            log.warn("错误补偿处理失败========================");
            //解决失败 存回去
            redisTemplate.opsForList().leftPush(MEMBER_MANAGER_API_KEY, JSONObject.toJSONString(verifyWxCodeCompensator));
        }
    }
}
